use ruma::api::{
    client::{error::ErrorKind, profile::get_profile},
    federation,
};

use crate::{server::server, utils::ruma_wrapper::Ruma, Error, Result};

/// # `GET /_matrix/client/v3/profile/{userId}`
///
/// Returns the displayname, avatar_url, blurhash, and tz of the user.
///
/// - If user is on another server and we do not have a local copy already,
///   fetch profile over federation.
pub(crate) async fn get_profile_route(
    body: Ruma<get_profile::v3::Request>,
) -> Result<get_profile::v3::Response> {
    if !server().config.user_is_local(&body.user_id) {
        // Create and update our local copy of the user
        if let Ok(response) = server()
            .sending
            .send_federation_request(
                body.user_id.server_name(),
                federation::query::get_profile_information::v1::Request {
                    user_id: body.user_id.clone(),
                    field: None,
                },
            )
            .await
        {
            if !server().users.exists(&body.user_id)? {
                server().users.create_user(&body.user_id, None)?;
            }

            // services
            //     .users
            //     .set_displayname(&body.user_id, response.displayname.clone())
            //     .await?;

            // for (profile_key, profile_key_value) in &response.custom_profile_fields {
            //     services.users.set_profile_key(
            //         &body.user_id,
            //         profile_key,
            //         Some(profile_key_value.clone()),
            //     )?;
            // }

            return Ok(get_profile::v3::Response {
                displayname: response.displayname,
                avatar_url: response.avatar_url,
            });
        }
    }

    if !server().users.exists(&body.user_id)? {
        // Return 404 if this user doesn't exist and we couldn't fetch it over
        // federation
        return Err(Error::BadRequest(
            ErrorKind::NotFound,
            "Profile was not found.",
        ));
    }

    Ok(get_profile::v3::Response {
        avatar_url: None,
        displayname: None,
    })
}
